"""
A* grid planning
"""

import math

import matplotlib.pyplot as plt
from matplotlib import rcParams
show_animation = True


class AStarPlanner:

    def __init__(self, ox, oy, resolution, rr):
        """
        Initialize grid map for a star planning
        ox: x position list of Obstacles [m]
        oy: y position list of Obstacles [m]
        resolution: grid resolution [m]
        rr: robot radius[m]
        """

        self.resolution = resolution
        self.rr = rr
        self.min_x, self.min_y = 0, 0
        self.max_x, self.max_y = 0, 0
        self.obstacle_map = None
        self.x_width, self.y_width = 0, 0
        self.motion = self.get_motion_model()
        self.calc_obstacle_map(ox, oy)

    class Node:
        def __init__(self, x, y, g_cost, h_cost, parent_index): # 基于A*原理和已有代码框架，修改了Node的结构，将原来的总cost改为两个子cost的数据结构（total_cost = g_cost + h_cost）
            self.x = x  # index of grid
            self.y = y  # index of grid
            self.g_cost = g_cost    # 移动代价g（离原点）Dijstra
            self.h_cost = h_cost    # 预测代价h（离终点）best first search
            self.parent_index = parent_index

        def __str__(self):
            return str(self.x) + "," + str(self.y) + "," + str(
                self.g_cost+self.h_cost) + "," + str(self.parent_index)

    def planning(self, sx, sy, gx, gy):
        """
        A star path search
        input:
            s_x: start x position [m]
            s_y: start y position [m]
            gx: goal x position [m]
            gy: goal y position [m]
        output:
            rx: x position list of the final path
            ry: y position list of the final path
        """

        start_node = self.Node(self.calc_xy_index(sx, self.min_x),
                               self.calc_xy_index(sy, self.min_y), 0.0, 0.0, -1)
        goal_node = self.Node(self.calc_xy_index(gx, self.min_x),
                              self.calc_xy_index(gy, self.min_y), 0.0, 0.0, -1) # 初始化的cost都为0

        open_set, closed_set = dict(), dict()
        open_set[self.calc_grid_index(start_node)] = start_node

        while 1:
            c_id = min(open_set, key=lambda o: (open_set[o].g_cost + open_set[o].h_cost))    # 选择最小total cost作为优先选择
            current = open_set[c_id]

            # show graph
            if show_animation:  # pragma: no cover
                plt.plot(self.calc_grid_position(current.x, self.min_x),
                         self.calc_grid_position(current.y, self.min_y), "xc")
                # for stopping simulation with the esc key.
                plt.gcf().canvas.mpl_connect(
                    'key_release_event',
                    lambda event: [exit(0) if event.key == 'escape' else None])
                if len(closed_set.keys()) % 10 == 0:
                    plt.pause(0.001)

            if current.x == goal_node.x and current.y == goal_node.y:
                print("Find goal")
                goal_node.parent_index = current.parent_index
                goal_node.g_cost = current.g_cost
                goal_node.h_cost = current.h_cost
                break

            # Remove the item from the open set
            del open_set[c_id]

            # Add it to the closed set
            closed_set[c_id] = current

            # expand search grid based on motion model
            for move_x, move_y, move_cost in self.motion:
                # move_next_cost = current.g_cost + move_cost    
                node_next = self.Node(current.x + move_x,   # 只需要用到下一个motion后的点坐标，用于计算其h_cost，因此后面三个参数可以随意设定；
                        current.y + move_y, 
                        0,
                        0,
                        c_id)
                node = self.Node(current.x + move_x,
                        current.y + move_y,
                        current.g_cost + move_cost,# 表示当前点执行一个motion后，新的总移动代价
                        self.calc_heuristic(node_next,goal_node),# 对每个点计算自己的h_cost
                        c_id)
                
                n_id = self.calc_grid_index(node)

                if n_id in closed_set:
                    continue

                if not self.verify_node(node):  # 判断该点是否是地图外的点和障碍物点
                    continue

                if n_id not in open_set:
                    open_set[n_id] = node  # Discover a new node
                else:
                    if (open_set[n_id].g_cost + open_set[n_id].h_cost) >= (node.g_cost + node.h_cost):
                        # This path is the best until now. record it!
                        open_set[n_id] = node

        rx, ry = self.calc_final_path(goal_node, closed_set)


        return rx, ry

    def calc_final_path(self, goal_node, closed_set):
        # generate final path
        rx, ry = [self.calc_grid_position(goal_node.x, self.min_x)], [
            self.calc_grid_position(goal_node.y, self.min_y)]
        parent_index = goal_node.parent_index
        while parent_index != -1:
            n = closed_set[parent_index]
            rx.append(self.calc_grid_position(n.x, self.min_x))
            ry.append(self.calc_grid_position(n.y, self.min_y))
            parent_index = n.parent_index

        return rx, ry

    @staticmethod
    def calc_heuristic(n1, n2):
        w = 1.5  # weight of heuristic
        d = w * math.hypot(n1.x - n2.x, n1.y - n2.y)    # 欧式距离
        return d

    def calc_grid_position(self, index, min_position):
        """
        calc grid position
        :param index:
        :param min_position:
        :return:
        """
        pos = index * self.resolution + min_position    # resolution为分辨率（2）
        return pos

    def calc_xy_index(self, position, min_pos):
        return round((position - min_pos) / self.resolution)

    def calc_grid_index(self, node):
        return (node.y - self.min_y) * self.x_width + (node.x - self.min_x)

    def verify_node(self, node):
        px = self.calc_grid_position(node.x, self.min_x)
        py = self.calc_grid_position(node.y, self.min_y)

        if px < self.min_x:
            return False
        elif py < self.min_y:
            return False
        elif px >= self.max_x:
            return False
        elif py >= self.max_y:
            return False

        # collision check
        if self.obstacle_map[node.x][node.y]:
            return False

        return True

    def calc_obstacle_map(self, ox, oy):

        self.min_x = round(min(ox))
        self.min_y = round(min(oy))
        self.max_x = round(max(ox))
        self.max_y = round(max(oy))
        print("min_x:", self.min_x)
        print("min_y:", self.min_y)
        print("max_x:", self.max_x)
        print("max_y:", self.max_y)

        self.x_width = round((self.max_x - self.min_x) / self.resolution)
        self.y_width = round((self.max_y - self.min_y) / self.resolution)
        print("x_width:", self.x_width)
        print("y_width:", self.y_width)

        # obstacle map generation
        self.obstacle_map = [[False for _ in range(self.y_width)]
                             for _ in range(self.x_width)]
        for ix in range(self.x_width):
            x = self.calc_grid_position(ix, self.min_x)
            for iy in range(self.y_width):
                y = self.calc_grid_position(iy, self.min_y)
                for iox, ioy in zip(ox, oy):
                    d = math.hypot(iox - x, ioy - y)
                    if d <= self.rr:
                        self.obstacle_map[ix][iy] = True
                        break

    @staticmethod
    def get_motion_model():
        # dx, dy, move_cost  8个方向
        motion = [[1, 0, 1],
                [0, 1, 1],
                [-1, 0, 1],
                [0, -1, 1],
                [-1, -1, math.sqrt(2)],
                [-1, 1, math.sqrt(2)],
                [1, -1, math.sqrt(2)],
                [1, 1, math.sqrt(2)]]

        return motion


def main():
    print(__file__ + " start!!")

    # obstacle属性修改处,只需要修改该处的数字即可，不再需要像原始代码那样修改多处
    min_x = -20
    min_y = -30
    max_x = 70
    max_y = 75
    # 障碍方案1 
    # linear_obs1_x = 20
    # linear_obs1_y_start = min_y 
    # linear_obs1_y_end = max_y - 20
    # linear_obs2_x = 40
    # linear_obs2_y_start = 20
    # linear_obs2_y_end = max_y
    # 障碍方案2
    # linear_obs1_x = 20
    # linear_obs1_y_start = 20
    # linear_obs1_y_end = 30
    # linear_obs2_x = 40
    # linear_obs2_y_start = 60
    # linear_obs2_y_end = max_y
    # # 障碍方案3
    linear_obs1_x = 17
    linear_obs1_y_start = min_y 
    linear_obs1_y_end = max_y - 31
    linear_obs2_x = 55
    linear_obs2_y_start = min_y + 5
    linear_obs2_y_end = max_y - 5

    # start and goal position
    sx = -15.0  # [m]
    sy = 23.0  # [m]
    gx = 65.0  # [m]
    gy = 33.0  # [m]
    grid_size = 3.0  # [m]
    robot_radius = 1.0  # [m]

    # set obstacle positions 
    ox, oy = [], []
    for i in range(min_y, max_y):
        ox.append(min_x)
        oy.append(i)
    for i in range(min_y, max_y):
        ox.append(max_x)
        oy.append(i)
    for i in range(min_x, max_x):
        ox.append(i)
        oy.append(min_y)
    for i in range(min_x, max_x):
        ox.append(i)
        oy.append(max_y)  # 设置地图边界完成，边界即为障碍物  下面为地图内部障碍物设置
    for i in range(linear_obs1_y_start, linear_obs1_y_end):
        ox.append(linear_obs1_x)
        oy.append(i)
    for i in range(linear_obs2_y_start, linear_obs2_y_end):
        ox.append(linear_obs2_x)
        oy.append(i)

    if show_animation:  # pragma: no cover

        config = {
            "font.family":'serif',  # 用来正常显示中文标签 Times New Roman字体
            "font.size": 16,
            "font.serif": ['SimSun'],
        }
        rcParams.update(config)
        plt.rcParams['axes.unicode_minus']=False    # 用来正常显示负号

        myfontdict = {'fontsize':16, 'color':'k'}
        plt.title('路径规划实验结果', fontdict = myfontdict)
        plt.plot(ox, oy, ".r", label='obstacle')  # 障碍物红色 点标记 
        plt.plot(sx, sy, "og", label='source point', markersize=5)  # 起点 绿色 圆标记
        plt.plot(gx, gy, "xm", label='goal point', markersize=5)  # 目标点洋红色 ×标记
        plt.grid(True)  # 显示网格线
        plt.axis("equal")   # x,y轴刻度等长
        plt.xlabel('x')
        plt.ylabel('y')

    a_star = AStarPlanner(ox, oy, grid_size, robot_radius)
    rx, ry = a_star.planning(sx, sy, gx, gy)

    if show_animation:  # pragma: no cover
        plt.plot(rx, ry, "-b", label='Optimal path') # 路径蓝色
        plt.pause(0.001)

    plt.legend()
    plt.show()


if __name__ == '__main__':
    main()
